import java.util.Date;
import java.util.Random;
import java.util.List;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import dao.ClassDAO;
import dao.GroupDAO;
import dao.RecordDAO;
import dao.StudentDAO;
import model.ClassInfo;
import model.Group;
import model.Record;
import model.Student;
import javax.swing.table.DefaultTableModel;
import javax.swing.filechooser.FileNameExtensionFilter;

public class Main {
    private static JFrame mainFrame;

    public static void main(String[] args) {
        // 设置UI风格为系统默认风格
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 创建主窗口
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

    private static void createAndShowGUI() {
        mainFrame = new JFrame("班级管理系统");
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setSize(800, 600);
        mainFrame.setLocationRelativeTo(null);

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout());

        // 创建顶部面板
        JPanel topPanel = new JPanel();
        topPanel.setBackground(new Color(51, 122, 183));
        JLabel titleLabel = new JLabel("班级管理系统");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(Color.WHITE);
        topPanel.add(titleLabel);

        // 创建功能按钮面板
        JPanel buttonPanel = new JPanel(new GridLayout(2, 2, 20, 20));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));

        JButton classBtn = createMenuButton("班级管理", "icons/class.png");
        JButton groupBtn = createMenuButton("小组管理", "icons/group.png");
        JButton studentBtn = createMenuButton("学生管理", "icons/student.png");
        JButton randomBtn = createMenuButton("随机点名", "icons/random.png");

        buttonPanel.add(classBtn);
        buttonPanel.add(groupBtn);
        buttonPanel.add(studentBtn);
        buttonPanel.add(randomBtn);

        // 添加事件监听
        classBtn.addActionListener(e -> showClassManagement());
        groupBtn.addActionListener(e -> showGroupManagement());
        studentBtn.addActionListener(e -> showStudentManagement());
        randomBtn.addActionListener(e -> showRandomCall());

        // 组装界面
        mainPanel.add(topPanel, BorderLayout.NORTH);
        mainPanel.add(buttonPanel, BorderLayout.CENTER);

        mainFrame.add(mainPanel);
        mainFrame.setVisible(true);
    }
//创建主窗口并设置基本属性
    private static JButton createMenuButton(String text, String iconPath) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        button.setPreferredSize(new Dimension(150, 100));
        return button;
    }
//创造菜单按钮
    private static void showClassManagement() {
        JDialog dialog = new JDialog(mainFrame, "班级管理", true);
        dialog.setSize(800, 600);
        dialog.setLocationRelativeTo(mainFrame);

        JPanel panel = new JPanel(new BorderLayout());

        // 创建工具栏
        JToolBar toolbar = new JToolBar();
        toolbar.setFloatable(false);

        JButton addBtn = new JButton("新增班级");
        JButton editBtn = new JButton("维护班级");
        JButton deleteBtn = new JButton("删除班级");
        JButton refreshBtn = new JButton("刷新");

        toolbar.add(addBtn);
        toolbar.add(editBtn);
        toolbar.add(deleteBtn);
        toolbar.add(refreshBtn);

        // 创建表格
        String[] columnNames = {"ID", "班级名称", "年级", "班主任", "学生人数", "描述"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        JTable table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);

        // 刷新表格数据的方法
        Runnable refreshTable = () -> {
            tableModel.setRowCount(0);
            for (ClassInfo classInfo : ClassDAO.getAllClasses()) {
                tableModel.addRow(new Object[]{
                    classInfo.getId(),
                    classInfo.getClassName(),
                    classInfo.getGrade(),
                    classInfo.getTeacher(),
                    classInfo.getStudentCount(),
                    classInfo.getDescription()
                });
            }
        };

        // 初始加载数据
        refreshTable.run();

        // 添加按钮事件
        addBtn.addActionListener(e -> showAddClassDialog(dialog, refreshTable));
        editBtn.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                int classId = (int) table.getValueAt(selectedRow, 0);
                showEditClassDialog(dialog, classId, refreshTable);
            } else {
                JOptionPane.showMessageDialog(dialog, "请先选择要编辑的班级！");
            }
        });//编辑班级
        deleteBtn.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                int classId = (int) table.getValueAt(selectedRow, 0);
                int confirm = JOptionPane.showConfirmDialog(dialog,
                    "确定要删除选中的班级吗？", "确认删除",
                    JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    ClassDAO.deleteClass(classId);
                    refreshTable.run();
                }
            } else {
                JOptionPane.showMessageDialog(dialog, "请先选择要删除的班级！");
            }
        });
        refreshBtn.addActionListener(e -> refreshTable.run());//删除班级

        panel.add(toolbar, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);

        dialog.add(panel);
        dialog.setVisible(true);
    }
//班级管理系统，显示班级管理对话框，包括新增、编辑、删除和刷新班级的功能。
    private static void showAddClassDialog(JDialog parent, Runnable refreshCallback) {
        JDialog dialog = new JDialog(parent, "新增班级", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(parent);

        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 创建表单
        gbc.gridx = 0; gbc.gridy = 0;
        panel.add(new JLabel("班级名称:"), gbc);
        gbc.gridx = 1;
        JTextField classNameField = new JTextField(20);
        panel.add(classNameField, gbc);

        gbc.gridx = 0; gbc.gridy = 1;
        panel.add(new JLabel("年级:"), gbc);
        gbc.gridx = 1;
        JTextField gradeField = new JTextField(20);
        panel.add(gradeField, gbc);

        gbc.gridx = 0; gbc.gridy = 2;
        panel.add(new JLabel("班主任:"), gbc);
        gbc.gridx = 1;
        JTextField teacherField = new JTextField(20);
        panel.add(teacherField, gbc);

        gbc.gridx = 0; gbc.gridy = 3;
        panel.add(new JLabel("描述:"), gbc);
        gbc.gridx = 1;
        JTextArea descArea = new JTextArea(3, 20);
        JScrollPane scrollPane = new JScrollPane(descArea);
        panel.add(scrollPane, gbc);

        // 添加按钮
        JPanel buttonPanel = new JPanel();
        JButton saveBtn = new JButton("保存");
        JButton cancelBtn = new JButton("取消");

        saveBtn.addActionListener(e -> {
            // 验证输入
            if (classNameField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "班级名称不能为空！");
                return;
            }

            // 创建新的班级对象
            ClassInfo newClass = new ClassInfo(
                0, // ID会在DAO中自动分配
                classNameField.getText().trim(),
                gradeField.getText().trim(),
                teacherField.getText().trim(),
                0, // 初始学生数为0
                descArea.getText().trim()
            );

            // 保存班级
            ClassDAO.addClass(newClass);

            // 刷新表格
            refreshCallback.run();

            dialog.dispose();
        });

        cancelBtn.addActionListener(e -> dialog.dispose());

        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);

        gbc.gridx = 0; gbc.gridy = 4;
        gbc.gridwidth = 2;
        panel.add(buttonPanel, gbc);

        dialog.add(panel);
        dialog.setVisible(true);
    }
//实现添加班级，包括班级名称，人数，班主任等
    private static void showEditClassDialog(JDialog parent, int classId, Runnable refreshCallback) {
        // 获取要编辑的班级信息
        ClassInfo classInfo = ClassDAO.getClassById(classId);
        if (classInfo == null) {
            JOptionPane.showMessageDialog(parent, "未找到班级信息！");
            return;
        }
        JDialog dialog = new JDialog(parent, "编辑班级", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(parent);

        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 创建表单并填充现有数据
        gbc.gridx = 0; gbc.gridy = 0;
        panel.add(new JLabel("班级名称:"), gbc);
        gbc.gridx = 1;
        JTextField classNameField = new JTextField(20);
        classNameField.setText(classInfo.getClassName());
        panel.add(classNameField, gbc);

        gbc.gridx = 0; gbc.gridy = 1;
        panel.add(new JLabel("年级:"), gbc);
        gbc.gridx = 1;
        JTextField gradeField = new JTextField(20);
        gradeField.setText(classInfo.getGrade());
        panel.add(gradeField, gbc);

        gbc.gridx = 0; gbc.gridy = 2;
        panel.add(new JLabel("班主任:"), gbc);
        gbc.gridx = 1;
        JTextField teacherField = new JTextField(20);
        teacherField.setText(classInfo.getTeacher());
        panel.add(teacherField, gbc);

        gbc.gridx = 0; gbc.gridy = 3;
        panel.add(new JLabel("学生人数:"), gbc);
        gbc.gridx = 1;
        JTextField studentCountField = new JTextField(20);
        studentCountField.setText(String.valueOf(classInfo.getStudentCount()));
        panel.add(studentCountField, gbc);

        gbc.gridx = 0; gbc.gridy = 4;
        panel.add(new JLabel("描述:"), gbc);
        gbc.gridx = 1;
        JTextArea descArea = new JTextArea(3, 20);
        descArea.setText(classInfo.getDescription());
        JScrollPane scrollPane = new JScrollPane(descArea);
        panel.add(scrollPane, gbc);

        // 添加按钮
        JPanel buttonPanel = new JPanel();
        JButton saveBtn = new JButton("保存");
        JButton cancelBtn = new JButton("取消");

        saveBtn.addActionListener(e -> {
            // 验证输入
            if (classNameField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "班级名称不能为空！");
                return;
            }

            try {
                int studentCount = Integer.parseInt(studentCountField.getText().trim());
                if (studentCount < 0) {
                    JOptionPane.showMessageDialog(dialog, "学生人数不能为负数！");
                    return;
                }

                // 更新班级信息
                classInfo.setClassName(classNameField.getText().trim());
                classInfo.setGrade(gradeField.getText().trim());
                classInfo.setTeacher(teacherField.getText().trim());
                classInfo.setStudentCount(studentCount);
                classInfo.setDescription(descArea.getText().trim());

                // 保存更新
                ClassDAO.updateClass(classInfo);

                // 刷新表格
                refreshCallback.run();

                JOptionPane.showMessageDialog(dialog, "保存成功！");
                dialog.dispose();

            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(dialog, "学生人数必须是有效的数字！");
            }
        });

        cancelBtn.addActionListener(e -> dialog.dispose());

        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);

        gbc.gridx = 0; gbc.gridy = 5;
        gbc.gridwidth = 2;
        panel.add(buttonPanel, gbc);

        dialog.add(panel);
        dialog.setVisible(true);
    }
//实现维护班级，修改班级的一系列信息
    private static void showGroupManagement() {
        JDialog dialog = new JDialog(mainFrame, "小组管理", true);
        dialog.setSize(800, 600);
        dialog.setLocationRelativeTo(mainFrame);

        JPanel panel = new JPanel(new BorderLayout());

        // 创建工具栏
        JToolBar toolbar = new JToolBar();
        toolbar.setFloatable(false);

        JButton addBtn = new JButton("新增小组");
        JButton editBtn = new JButton("维护小组");
        JButton deleteBtn = new JButton("删除小组");
        JButton refreshBtn = new JButton("刷新");
        JButton viewMembersBtn = new JButton("查看小组成员"); // 新增按钮

        toolbar.add(addBtn);
        toolbar.add(editBtn);
        toolbar.add(deleteBtn);
        toolbar.add(refreshBtn);
        toolbar.add(viewMembersBtn); // 添加到工具栏

        // 创建表格
        String[] columnNames = {"ID", "小组名称", "所属班级", "组长", "组员数量", "描述"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        JTable table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);

        // 刷新表格数据的方法
        Runnable refreshTable = () -> {
            tableModel.setRowCount(0);
            for (Group group : GroupDAO.getAllGroups()) {
                ClassInfo classInfo = ClassDAO.getClassById(group.getClassId());
                String className = classInfo != null ? classInfo.getClassName() : "未知班级";
                tableModel.addRow(new Object[]{
                    group.getId(),
                    group.getGroupName(),
                    className,
                    group.getLeader(),
                    group.getMemberCount(),
                    group.getDescription()
                });
            }
        };

        // 初始加载数据
        refreshTable.run();

        // 添加按钮事件
        addBtn.addActionListener(e -> showAddGroupDialog(dialog, refreshTable));
        editBtn.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                int groupId = (int) table.getValueAt(selectedRow, 0);
                showEditGroupDialog(dialog, groupId, refreshTable);
            } else {
                JOptionPane.showMessageDialog(dialog, "请先选择要编辑的小组！");
            }
        });
        deleteBtn.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                int groupId = (int) table.getValueAt(selectedRow, 0);
                int confirm = JOptionPane.showConfirmDialog(dialog,
                    "确定要删除选中的小组吗？", "确认删除",
                    JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    GroupDAO.deleteGroup(groupId);
                    refreshTable.run();
                }
            } else {
                JOptionPane.showMessageDialog(dialog, "请先选择要删除的小组！");
            }
        });
        refreshBtn.addActionListener(e -> refreshTable.run());

        // 新增查看小组成员的事件
        viewMembersBtn.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                int groupId = (int) table.getValueAt(selectedRow, 0);
                showGroupMembersDialog(dialog, groupId); // 调用查看小组成员的方法
            } else {
                JOptionPane.showMessageDialog(dialog, "请先选择要查看的小组！");
            }
        });

        panel.add(toolbar, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);

        dialog.add(panel);
        dialog.setVisible(true);
    }
//小组管理系统，包括新增、编辑、删除、刷新和查看小组等功能
    private static void showGroupMembersDialog(JDialog parent, int groupId) {
        Group group = GroupDAO.getGroupById(groupId);
        if (group == null) {
            JOptionPane.showMessageDialog(parent, "未找到小组信息！");
            return;
        }

        JDialog dialog = new JDialog(parent, "小组成员 - " + group.getGroupName(), true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(parent);

        JPanel panel = new JPanel(new BorderLayout());
        JTextArea membersArea = new JTextArea();
        membersArea.setEditable(false);

        // 获取小组成员
        List<Student> members = StudentDAO.getStudentsByGroupId(groupId);
        StringBuilder membersList = new StringBuilder();
        for (Student member : members) {
            membersList.append(member.getStudentName()).append("\n");
        }
        membersArea.setText(membersList.toString());

        panel.add(new JScrollPane(membersArea), BorderLayout.CENTER);
        dialog.add(panel);
        dialog.setVisible(true);
    }
//显示小组成员
    private static void showAddGroupDialog(JDialog parent, Runnable refreshCallback) {
        JDialog dialog = new JDialog(parent, "新增小组", true);
        dialog.setSize(400, 350);
        dialog.setLocationRelativeTo(parent);

        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 创建表单
        gbc.gridx = 0; gbc.gridy = 0;
        panel.add(new JLabel("小组名称:"), gbc);
        gbc.gridx = 1;
        JTextField groupNameField = new JTextField(20);
        panel.add(groupNameField, gbc);

        // 班级选择下拉框
        gbc.gridx = 0; gbc.gridy = 1;
        panel.add(new JLabel("所属班级:"), gbc);
        gbc.gridx = 1;
        JComboBox<ClassInfo> classComboBox = new JComboBox<>();
        for (ClassInfo classInfo : ClassDAO.getAllClasses()) {
            classComboBox.addItem(classInfo);
        }
        classComboBox.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                if (value instanceof ClassInfo) {
                    value = ((ClassInfo)value).getClassName();
                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }
        });
        panel.add(classComboBox, gbc);

        gbc.gridx = 0; gbc.gridy = 2;
        panel.add(new JLabel("组长:"), gbc);
        gbc.gridx = 1;
        JTextField leaderField = new JTextField(20);
        panel.add(leaderField, gbc);

        gbc.gridx = 0; gbc.gridy = 3;
        panel.add(new JLabel("组员数量:"), gbc);
        gbc.gridx = 1;
        JTextField memberCountField = new JTextField("0", 20);
        panel.add(memberCountField, gbc);

        gbc.gridx = 0; gbc.gridy = 4;
        panel.add(new JLabel("描述:"), gbc);
        gbc.gridx = 1;
        JTextArea descArea = new JTextArea(3, 20);
        JScrollPane scrollPane = new JScrollPane(descArea);
        panel.add(scrollPane, gbc);

        // 添加按钮
        JPanel buttonPanel = new JPanel();
        JButton saveBtn = new JButton("保存");
        JButton cancelBtn = new JButton("取消");

        saveBtn.addActionListener(e -> {
            // 验证输入
            if (groupNameField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "小组名称不能为空！");
                return;
            }

            if (classComboBox.getSelectedItem() == null) {
                JOptionPane.showMessageDialog(dialog, "请选择所属班级！");
                return;
            }

            try {
                int memberCount = Integer.parseInt(memberCountField.getText().trim());
                if (memberCount < 0) {
                    JOptionPane.showMessageDialog(dialog, "组员数量不能为负数！");
                    return;
                }

                // 创建新的小组对象
                ClassInfo selectedClass = (ClassInfo) classComboBox.getSelectedItem();
                Group newGroup = new Group(
                    0, // ID会在DAO中自动分配
                    groupNameField.getText().trim(),
                    selectedClass.getId(),
                    leaderField.getText().trim(),
                    memberCount,
                    descArea.getText().trim()
                );

                // 保存小组
                GroupDAO.addGroup(newGroup);

                // 刷新表格
                refreshCallback.run();

                dialog.dispose();

            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(dialog, "组员数量必须是有效的数字！");
            }
        });

        cancelBtn.addActionListener(e -> dialog.dispose());

        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);

        gbc.gridx = 0; gbc.gridy = 5;
        gbc.gridwidth = 2;
        panel.add(buttonPanel, gbc);

        dialog.add(panel);
        dialog.setVisible(true);
    }
//添加小组，小组班级，名称，人数，班级，组长
    private static void showEditGroupDialog(JDialog parent, int groupId, Runnable refreshCallback) {
        Group group = GroupDAO.getGroupById(groupId);
        if (group == null) {
            JOptionPane.showMessageDialog(parent, "未找到小组信息！");
            return;
        }

        JDialog dialog = new JDialog(parent, "编辑小组", true);
        dialog.setSize(400, 350);
        dialog.setLocationRelativeTo(parent);

        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 创建表单并填充现有数据
        gbc.gridx = 0; gbc.gridy = 0;
        panel.add(new JLabel("小组名称:"), gbc);
        gbc.gridx = 1;
        JTextField groupNameField = new JTextField(group.getGroupName(), 20);
        panel.add(groupNameField, gbc);

        // 班级选择下拉框
        gbc.gridx = 0; gbc.gridy = 1;
        panel.add(new JLabel("所属班级:"), gbc);
        gbc.gridx = 1;
        JComboBox<ClassInfo> classComboBox = new JComboBox<>();
        for (ClassInfo classInfo : ClassDAO.getAllClasses()) {
            classComboBox.addItem(classInfo);
            if (classInfo.getId() == group.getClassId()) {
                classComboBox.setSelectedItem(classInfo);
            }
        }
        classComboBox.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                if (value instanceof ClassInfo) {
                    value = ((ClassInfo)value).getClassName();
                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }
        });
        panel.add(classComboBox, gbc);

        gbc.gridx = 0; gbc.gridy = 2;
        panel.add(new JLabel("组长:"), gbc);
        gbc.gridx = 1;
        JTextField leaderField = new JTextField(group.getLeader(), 20);
        panel.add(leaderField, gbc);

        gbc.gridx = 0; gbc.gridy = 3;
        panel.add(new JLabel("组员数量:"), gbc);
        gbc.gridx = 1;
        JTextField memberCountField = new JTextField(String.valueOf(group.getMemberCount()), 20);
        panel.add(memberCountField, gbc);

        gbc.gridx = 0; gbc.gridy = 4;
        panel.add(new JLabel("描述:"), gbc);
        gbc.gridx = 1;
        JTextArea descArea = new JTextArea(group.getDescription(), 3, 20);
        JScrollPane scrollPane = new JScrollPane(descArea);
        panel.add(scrollPane, gbc);

        // 添加按钮
        JPanel buttonPanel = new JPanel();
        JButton saveBtn = new JButton("保存");
        JButton cancelBtn = new JButton("取消");

        saveBtn.addActionListener(e -> {
            // 验证输入
            if (groupNameField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "小组名不能为空！");
                return;
            }

            try {
                int memberCount = Integer.parseInt(memberCountField.getText().trim());
                if (memberCount < 0) {
                    JOptionPane.showMessageDialog(dialog, "组员数量不能为负数！");
                    return;
                }

                // 更新小组信息
                ClassInfo selectedClass = (ClassInfo) classComboBox.getSelectedItem();
                group.setGroupName(groupNameField.getText().trim());
                group.setClassId(selectedClass.getId());
                group.setLeader(leaderField.getText().trim());
                group.setMemberCount(memberCount);
                group.setDescription(descArea.getText().trim());

                // 保存更新
                GroupDAO.updateGroup(group);

                // 刷新表格
                refreshCallback.run();

                JOptionPane.showMessageDialog(dialog, "保存成功！");
                dialog.dispose();

            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(dialog, "组员数量必须是有效的数字！");
            }
        });

        cancelBtn.addActionListener(e -> dialog.dispose());

        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);

        gbc.gridx = 0; gbc.gridy = 5;
        gbc.gridwidth = 2;
        panel.add(buttonPanel, gbc);

        dialog.add(panel);
        dialog.setVisible(true);
    }
//编辑小组信息
    private static void showStudentManagement() {
        JDialog dialog = new JDialog(mainFrame, "学生管理", true);
        dialog.setSize(800, 600);
        dialog.setLocationRelativeTo(mainFrame);

        JPanel panel = new JPanel(new BorderLayout());

        // 创建工具栏
        JToolBar toolbar = new JToolBar();
        toolbar.setFloatable(false);

        JButton addBtn = new JButton("新增学生");
        JButton editBtn = new JButton("维护学生");
        JButton deleteBtn = new JButton("删除学生");
        JButton refreshBtn = new JButton("刷新");

        toolbar.add(addBtn);
        toolbar.add(editBtn);
        toolbar.add(deleteBtn);
        toolbar.add(refreshBtn);

        // 创建表格
        String[] columnNames = {"ID", "姓名", "学号", "班级", "小组", "性别", "描述"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        JTable table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);

        // 刷新表格数据的方法
        Runnable refreshTable = () -> {
            tableModel.setRowCount(0);
            for (Student student : StudentDAO.getAllStudents()) {
                ClassInfo classInfo = ClassDAO.getClassById(student.getClassId());
                Group group = GroupDAO.getGroupById(student.getGroupId());
                String className = classInfo != null ? classInfo.getClassName() : "未分配";
                String groupName = group != null ? group.getGroupName() : "未分配";

                tableModel.addRow(new Object[]{
                    student.getId(),
                    student.getStudentName(),
                    student.getStudentId(),
                    className,
                    groupName,
                    student.getGender(),
                    student.getDescription()
                });
            }
        };

        // 初始加载数据
        refreshTable.run();

        // 添加按钮事件
        addBtn.addActionListener(e -> showAddStudentDialog(dialog, refreshTable));
        editBtn.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                int studentId = (int) table.getValueAt(selectedRow, 0);
                showEditStudentDialog(dialog, studentId, refreshTable);
            } else {
                JOptionPane.showMessageDialog(dialog, "请先选择要编辑的学生！");
            }
        });
        //删除学生信息事件
        deleteBtn.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                int studentId = (int) table.getValueAt(selectedRow, 0);
                int confirm = JOptionPane.showConfirmDialog(dialog,
                    "确定要删除选中的学生吗？", "确认删除",
                    JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    StudentDAO.deleteStudent(studentId);
                    refreshTable.run();
                }
            } else {
                JOptionPane.showMessageDialog(dialog, "请先选择要删除的学生！");
            }
        });
        refreshBtn.addActionListener(e -> refreshTable.run());

        panel.add(toolbar, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);

        dialog.add(panel);
        dialog.setVisible(true);
    }
//学生管理系统，定义新增学生，维护学生，删除学生等功能
    private static void showAddStudentDialog(JDialog parent, Runnable refreshCallback) {
        JDialog dialog = new JDialog(parent, "新增学生", true);
        dialog.setSize(400, 500);
        dialog.setLocationRelativeTo(parent);

        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 创建表单
        int gridy = 0;

        // 姓名
        gbc.gridx = 0; gbc.gridy = gridy++;
        panel.add(new JLabel("姓名:"), gbc);
        gbc.gridx = 1;
        JTextField nameField = new JTextField(20);
        panel.add(nameField, gbc);

        // 学号
        gbc.gridx = 0; gbc.gridy = gridy++;
        panel.add(new JLabel("学号:"), gbc);
        gbc.gridx = 1;
        JTextField studentIdField = new JTextField(20);
        panel.add(studentIdField, gbc);

        // 班级选择
        gbc.gridx = 0; gbc.gridy = gridy++;
        panel.add(new JLabel("班级:"), gbc);
        gbc.gridx = 1;
        JComboBox<ClassInfo> classComboBox = new JComboBox<>();
        classComboBox.addItem(null);  // 添加空
        for (ClassInfo classInfo : ClassDAO.getAllClasses()) {
            classComboBox.addItem(classInfo);
        }
        classComboBox.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                if (value == null) {
                    value = "请选择班级";
                } else if (value instanceof ClassInfo) {
                    value = ((ClassInfo)value).getClassName();
                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }
        });
        panel.add(classComboBox, gbc);

        // 小组选择
        gbc.gridx = 0; gbc.gridy = gridy++;
        panel.add(new JLabel("小组:"), gbc);
        gbc.gridx = 1;
        JComboBox<Group> groupComboBox = new JComboBox<>();
        groupComboBox.addItem(null);  // 添加空选项
        groupComboBox.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                if (value == null) {
                    value = "请选择小组";
                } else if (value instanceof Group) {
                    value = ((Group)value).getGroupName();
                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }
        });
        panel.add(groupComboBox, gbc);

        // 当班级选择改变时更新小组列表
        classComboBox.addActionListener(e -> {
            groupComboBox.removeAllItems();
            groupComboBox.addItem(null);
            ClassInfo selectedClass = (ClassInfo) classComboBox.getSelectedItem();
            if (selectedClass != null) {
                for (Group group : GroupDAO.getGroupsByClassId(selectedClass.getId())) {
                    groupComboBox.addItem(group);
                }
            }
        });

        // 性别
        gbc.gridx = 0; gbc.gridy = gridy++;
        panel.add(new JLabel("性别:"), gbc);
        gbc.gridx = 1;
        JComboBox<String> genderComboBox = new JComboBox<>(new String[]{"男", "女"});
        panel.add(genderComboBox, gbc);

        // 描述
        gbc.gridx = 0; gbc.gridy = gridy++;
        panel.add(new JLabel("描述:"), gbc);
        gbc.gridx = 1;
        JTextArea descArea = new JTextArea(3, 20);
        JScrollPane scrollPane = new JScrollPane(descArea);
        panel.add(scrollPane, gbc);

        // 添加按钮
        JPanel buttonPanel = new JPanel();
        JButton saveBtn = new JButton("保存");
        JButton cancelBtn = new JButton("取消");

        saveBtn.addActionListener(e -> {
            // 验证输入
            if (nameField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "姓名不能为空！");
                return;
            }
            if (studentIdField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "学号不能为空！");
                return;
            }
            if (classComboBox.getSelectedItem() == null) {
                JOptionPane.showMessageDialog(dialog, "请选择班级！");
                return;
            }

            // 创建新的学生对象
            ClassInfo selectedClass = (ClassInfo) classComboBox.getSelectedItem();
            Group selectedGroup = (Group) groupComboBox.getSelectedItem();

            // 获取当前最大ID并加1
            int newId = StudentDAO.getMaxId() + 1; // 假设你有一个方法来获取最大ID

            Student newStudent = new Student(
                newId, // 使用新生成的ID
                nameField.getText().trim(),
                studentIdField.getText().trim(),
                selectedClass.getId(),
                selectedGroup != null ? selectedGroup.getId() : 0,
                (String) genderComboBox.getSelectedItem(),
                descArea.getText().trim()
            );

            // 保存学生
            StudentDAO.addStudent(newStudent);

            // 更新班级学生数量
            selectedClass.setStudentCount(selectedClass.getStudentCount() + 1);
            ClassDAO.updateClass(selectedClass);

            // 更新小组成员数量
            if (selectedGroup != null) {
                selectedGroup.setMemberCount(selectedGroup.getMemberCount() + 1);
                GroupDAO.updateGroup(selectedGroup);
            }

            // 刷新表格
            refreshCallback.run();

            dialog.dispose();
        });

        cancelBtn.addActionListener(e -> dialog.dispose());

        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);

        gbc.gridx = 0; gbc.gridy = gridy;
        gbc.gridwidth = 2;
        panel.add(buttonPanel, gbc);

        dialog.add(panel);
        dialog.setVisible(true);
    }
//新增学生信息，学号，班级，小组
    private static void showEditStudentDialog(JDialog parent, int studentId, Runnable refreshCallback) {
        Student student = StudentDAO.getStudentById(studentId);
        if (student == null) {
            JOptionPane.showMessageDialog(parent, "未找到学生信息！");
            return;
        }

        JDialog dialog = new JDialog(parent, "编辑学生", true);
        dialog.setSize(400, 500);
        dialog.setLocationRelativeTo(parent);

        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        int gridy = 0;

        // 姓名
        gbc.gridx = 0; gbc.gridy = gridy++;
        panel.add(new JLabel("姓名:"), gbc);
        gbc.gridx = 1;
        JTextField nameField = new JTextField(student.getStudentName(), 20);
        panel.add(nameField, gbc);

        // 学号
        gbc.gridx = 0; gbc.gridy = gridy++;
        panel.add(new JLabel("学号:"), gbc);
        gbc.gridx = 1;
        JTextField studentIdField = new JTextField(student.getStudentId(), 20);
        panel.add(studentIdField, gbc);

        // 班级选择
        gbc.gridx = 0; gbc.gridy = gridy++;
        panel.add(new JLabel("班级:"), gbc);
        gbc.gridx = 1;
        JComboBox<ClassInfo> classComboBox = new JComboBox<>();
        for (ClassInfo classInfo : ClassDAO.getAllClasses()) {
            classComboBox.addItem(classInfo);
            if (classInfo.getId() == student.getClassId()) {
                classComboBox.setSelectedItem(classInfo);
            }
        }
        classComboBox.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                if (value instanceof ClassInfo) {
                    value = ((ClassInfo)value).getClassName();
                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }
        });
        panel.add(classComboBox, gbc);

        // 小组选择
        gbc.gridx = 0; gbc.gridy = gridy++;
        panel.add(new JLabel("小组:"), gbc);
        gbc.gridx = 1;
        JComboBox<Group> groupComboBox = new JComboBox<>();
        groupComboBox.addItem(null);
        for (Group group : GroupDAO.getGroupsByClassId(student.getClassId())) {
            groupComboBox.addItem(group);
            if (group.getId() == student.getGroupId()) {
                groupComboBox.setSelectedItem(group);
            }
        }
        groupComboBox.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                if (value == null) {
                    value = "未分配小组";
                } else if (value instanceof Group) {
                    value = ((Group)value).getGroupName();
                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }
        });
        panel.add(groupComboBox, gbc);

        // 当班级选择改变时更新小组列表
        classComboBox.addActionListener(e -> {
            Group selectedGroup = (Group) groupComboBox.getSelectedItem();
            groupComboBox.removeAllItems();
            groupComboBox.addItem(null);
            ClassInfo selectedClass = (ClassInfo) classComboBox.getSelectedItem();
            if (selectedClass != null) {
                for (Group group : GroupDAO.getGroupsByClassId(selectedClass.getId())) {
                    groupComboBox.addItem(group);
                    if (selectedGroup != null && group.getId() == selectedGroup.getId()) {
                        groupComboBox.setSelectedItem(group);
                    }
                }
            }
        });

        // 性别
        gbc.gridx = 0; gbc.gridy = gridy++;
        panel.add(new JLabel("性别:"), gbc);
        gbc.gridx = 1;
        JComboBox<String> genderComboBox = new JComboBox<>(new String[]{"男", "女"});
        genderComboBox.setSelectedItem(student.getGender());
        panel.add(genderComboBox, gbc);

        // 描述
        gbc.gridx = 0; gbc.gridy = gridy++;
        panel.add(new JLabel("描述:"), gbc);
        gbc.gridx = 1;
        JTextArea descArea = new JTextArea(student.getDescription(), 3, 20);
        JScrollPane scrollPane = new JScrollPane(descArea);
        panel.add(scrollPane, gbc);

        // 添加按钮
        JPanel buttonPanel = new JPanel();
        JButton saveBtn = new JButton("保存");
        JButton cancelBtn = new JButton("取消");

        saveBtn.addActionListener(e -> {
            // 验证输入
            if (nameField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "姓名不能为空！");
                return;
            }
            if (studentIdField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "学号不能为空！");
                return;
            }

            // 获取原班级和小组
            ClassInfo oldClass = ClassDAO.getClassById(student.getClassId());
            Group oldGroup = GroupDAO.getGroupById(student.getGroupId());

            // 获取新班级和小组
            ClassInfo newClass = (ClassInfo) classComboBox.getSelectedItem();
            Group newGroup = (Group) groupComboBox.getSelectedItem();

            // 更新学生信息
            student.setStudentName(nameField.getText().trim());
            student.setStudentId(studentIdField.getText().trim());
            student.setClassId(newClass.getId());
            student.setGroupId(newGroup != null ? newGroup.getId() : 0);
            student.setGender((String) genderComboBox.getSelectedItem());
            student.setDescription(descArea.getText().trim());

            // 更新班级学生数量
            if (oldClass.getId() != newClass.getId()) {
                oldClass.setStudentCount(oldClass.getStudentCount() - 1);
                newClass.setStudentCount(newClass.getStudentCount() + 1);
                ClassDAO.updateClass(oldClass);
                ClassDAO.updateClass(newClass);
            }

            // 更新小组成员数量
            if (oldGroup != null && (newGroup == null || oldGroup.getId() != newGroup.getId())) {
                oldGroup.setMemberCount(oldGroup.getMemberCount() - 1);
                GroupDAO.updateGroup(oldGroup);
            }
            if (newGroup != null && (oldGroup == null || oldGroup.getId() != newGroup.getId())) {
                newGroup.setMemberCount(newGroup.getMemberCount() + 1);
                GroupDAO.updateGroup(newGroup);
            }

            // 保存更新
            StudentDAO.updateStudent(student);

            // 刷新表格
            refreshCallback.run();

            JOptionPane.showMessageDialog(dialog, "保存成功！");
            dialog.dispose();
        });

        cancelBtn.addActionListener(e -> dialog.dispose());

        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);

        gbc.gridx = 0; gbc.gridy = gridy;
        gbc.gridwidth = 2;
        panel.add(buttonPanel, gbc);

        dialog.add(panel);
        dialog.setVisible(true);
    }
//维护学生信息
    private static void showRandomCall() {
        JDialog dialog = new JDialog(mainFrame, "随机点名系统", true);
        dialog.setSize(800, 600);
        dialog.setLocationRelativeTo(mainFrame);

        JPanel panel = new JPanel(new BorderLayout());

        // 创建左侧面板用于显示班级和小组
        JPanel leftPanel = new JPanel(new BorderLayout());
        leftPanel.setBorder(BorderFactory.createTitledBorder("选择班级和小组"));

        // 班级选择
        JComboBox<ClassInfo> classComboBox = new JComboBox<>();
        classComboBox.addItem(null);
        for (ClassInfo classInfo : ClassDAO.getAllClasses()) {
            classComboBox.addItem(classInfo);
        }
        classComboBox.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value,
                    int index, boolean isSelected, boolean cellHasFocus) {
                if (value == null) {
                    value = "请选择班级";
                } else if (value instanceof ClassInfo) {
                    value = ((ClassInfo)value).getClassName();
                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }
        });

        // 小组选择
        JComboBox<Group> groupComboBox = new JComboBox<>();
        groupComboBox.addItem(null);
        groupComboBox.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value,
                    int index, boolean isSelected, boolean cellHasFocus) {
                if (value == null) {
                    value = "请选择小组";
                } else if (value instanceof Group) {
                    value = ((Group)value).getGroupName();
                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }
        });

        // 当班级选择改变时更新小组列表
        classComboBox.addActionListener(e -> {
            groupComboBox.removeAllItems();
            groupComboBox.addItem(null);
            ClassInfo selectedClass = (ClassInfo) classComboBox.getSelectedItem();
            if (selectedClass != null) {
                for (Group group : GroupDAO.getGroupsByClassId(selectedClass.getId())) {
                    groupComboBox.addItem(group);
                }
            }
        });

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new GridLayout(6, 1, 5, 5));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        JButton randomGroupBtn = new JButton("随机抽取小组");
        JButton randomStudentInGroupBtn = new JButton("随机抽取小组内学生");
        JButton randomStudentInClassBtn = new JButton("随机抽取班级内学生");
        JButton scoreBtn = new JButton("小组评分");
        JButton attendanceBtn = new JButton("记录考勤");
        JButton exportBtn = new JButton("导出成绩");

        // 创建结果显示区域
        JPanel resultPanel = new JPanel(new BorderLayout());
        resultPanel.setBorder(BorderFactory.createTitledBorder("结果显示"));
        JTextArea resultArea = new JTextArea();
        resultArea.setEditable(false);
        resultPanel.add(new JScrollPane(resultArea), BorderLayout.CENTER);

        // 添加按钮事件
        randomGroupBtn.addActionListener(e -> {
            ClassInfo selectedClass = (ClassInfo) classComboBox.getSelectedItem();
            if (selectedClass == null) {
                JOptionPane.showMessageDialog(dialog, "请先选择班级！");
                return;
            }
            List<Group> groups = GroupDAO.getGroupsByClassId(selectedClass.getId());
            if (groups.isEmpty()) {
                resultArea.setText("该班级还没有小组！");
                return;
            }
            Random random = new Random();
            Group selectedGroup = groups.get(random.nextInt(groups.size()));
            resultArea.setText("随机抽取的小组是：" + selectedGroup.getGroupName());
        });

        randomStudentInGroupBtn.addActionListener(e -> {
            Group selectedGroup = (Group) groupComboBox.getSelectedItem();
            if (selectedGroup == null) {
                JOptionPane.showMessageDialog(dialog, "请先选择小组！");
                return;
            }
            List<Student> students = StudentDAO.getStudentsByGroupId(selectedGroup.getId());
            if (students.isEmpty()) {
                resultArea.setText("该小组还没有学生！");
                return;
            }
            Random random = new Random();
            Student selectedStudent = students.get(random.nextInt(students.size()));
            resultArea.setText("随机抽取的学生是：" + selectedStudent.getStudentName());
        });

        randomStudentInClassBtn.addActionListener(e -> {
            ClassInfo selectedClass = (ClassInfo) classComboBox.getSelectedItem();
            if (selectedClass == null) {
                JOptionPane.showMessageDialog(dialog, "请先选择班级！");
                return;
            }
            List<Student> students = StudentDAO.getStudentsByClassId(selectedClass.getId());
            if (students.isEmpty()) {
                resultArea.setText("该班级还没有学生！");
                return;
            }
            Random random = new Random();
            Student selectedStudent = students.get(random.nextInt(students.size()));
            resultArea.setText("随机抽取的学生是：" + selectedStudent.getStudentName());
        });

        scoreBtn.addActionListener(e -> showGroupScoreDialog(dialog));
        attendanceBtn.addActionListener(e -> showAttendanceDialog(dialog));
        exportBtn.addActionListener(e -> exportScores(dialog));

        // 组装界面
        JPanel selectionPanel = new JPanel(new GridLayout(2, 1, 5, 5));
        selectionPanel.add(classComboBox);
        selectionPanel.add(groupComboBox);
        leftPanel.add(selectionPanel, BorderLayout.NORTH);
        leftPanel.add(buttonPanel, BorderLayout.CENTER);

        buttonPanel.add(randomGroupBtn);
        buttonPanel.add(randomStudentInGroupBtn);
        buttonPanel.add(randomStudentInClassBtn);
        buttonPanel.add(scoreBtn);
        buttonPanel.add(attendanceBtn);
        buttonPanel.add(exportBtn);

        panel.add(leftPanel, BorderLayout.WEST);
        panel.add(resultPanel, BorderLayout.CENTER);

        dialog.add(panel);
        dialog.setVisible(true);
    }
//随机点名系统，从班级，从小组中随机抽取学生，随机抽取小组
    private static void showGroupScoreDialog(JDialog parent) {
        JDialog dialog = new JDialog(parent, "小组评分", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(parent);

        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 创建表单
        gbc.gridx = 0; gbc.gridy = 0;
        panel.add(new JLabel("小组:"), gbc);
        gbc.gridx = 1;
        JComboBox<Group> groupComboBox = new JComboBox<>();
        groupComboBox.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value,
                    int index, boolean isSelected, boolean cellHasFocus) {
                if (value instanceof Group) {
                    value = ((Group)value).getGroupName();
                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }
        });
        for (Group group : GroupDAO.getAllGroups()) {
            groupComboBox.addItem(group);
        }
        panel.add(groupComboBox, gbc);

        gbc.gridx = 0; gbc.gridy = 1;
        panel.add(new JLabel("得分:"), gbc);
        gbc.gridx = 1;
        JSpinner scoreSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 100, 1));
        panel.add(scoreSpinner, gbc);

        gbc.gridx = 0; gbc.gridy = 2;
        panel.add(new JLabel("备注:"), gbc);
        gbc.gridx = 1;
        JTextArea notesArea = new JTextArea(3, 20);
        panel.add(new JScrollPane(notesArea), gbc);

        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(e -> {
            Group selectedGroup = (Group) groupComboBox.getSelectedItem();
            if (selectedGroup != null) {
                Record record = new Record(
                    0,
                    0, // 小组评分时不记录具体学生
                    selectedGroup.getId(),
                    new Date(),
                    true,
                    (Integer) scoreSpinner.getValue(),
                    notesArea.getText().trim()
                );
                RecordDAO.addRecord(record);

                // 在结果显示区域显示评分记录
                Component[] components = parent.getContentPane().getComponents();
                for (Component component : components) {
                    if (component instanceof JPanel &&
                        ((JPanel)component).getBorder() != null &&
                        ((JPanel)component).getBorder().toString().contains("结果显示")) {

                        JTextArea resultArea = (JTextArea) ((JScrollPane)((JPanel)component).getComponent(0))
                            .getViewport().getView();
                        resultArea.setText(String.format(
                            "评分记录：\n" +
                            "小组：%s\n" +
                            "得分：%d\n" +
                            "备注：%s\n" +
                            "时间：%s",
                            selectedGroup.getGroupName(),
                            record.getScore(),
                            record.getNotes(),
                            new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(record.getRecordDate())
                        ));
                        break;
                    }
                }

                dialog.dispose();
            }
        });

        gbc.gridx = 0; gbc.gridy = 3;
        gbc.gridwidth = 2;
        panel.add(saveBtn, gbc);

        dialog.add(panel);
        dialog.setVisible(true);
    }
//展示小组得分
    private static void showAttendanceDialog(JDialog parent) {
        JDialog dialog = new JDialog(parent, "记录考勤", true);
        dialog.setSize(600, 400);
        dialog.setLocationRelativeTo(parent);

        JPanel panel = new JPanel(new BorderLayout());

        // 创建表格
        String[] columnNames = {"学生姓名", "学号", "班级", "小组", "考勤", "得分", "备注"};
        DefaultTableModel model = new DefaultTableModel(columnNames, 0);
        JTable table = new JTable(model);

        // 添加考勤和得分的编辑组件
        table.getColumnModel().getColumn(4).setCellEditor(new DefaultCellEditor(
            new JComboBox<>(new String[]{"出席", "缺席"})));
        table.getColumnModel().getColumn(5).setCellEditor(new DefaultCellEditor(
            new JTextField()));

        // 加载学生数据
        for (Student student : StudentDAO.getAllStudents()) {
            ClassInfo classInfo = ClassDAO.getClassById(student.getClassId());
            Group group = GroupDAO.getGroupById(student.getGroupId());
            model.addRow(new Object[]{
                student.getStudentName(),
                student.getStudentId(),
                classInfo != null ? classInfo.getClassName() : "",
                group != null ? group.getGroupName() : "",
                "出席",
                "0",
                ""
            });
        }

        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(e -> {
            // 保存考勤记录
            for (int i = 0; i < model.getRowCount(); i++) {
                String studentName = (String) model.getValueAt(i, 0);
                String attendance = (String) model.getValueAt(i, 4);
                String scoreStr = (String) model.getValueAt(i, 5);
                String notes = (String) model.getValueAt(i, 6);

                Student student = StudentDAO.getAllStudents().get(i);
                try {
                    int score = Integer.parseInt(scoreStr);
                    Record record = new Record(
                        0,
                        student.getId(),
                        student.getGroupId(),
                        new Date(),
                        "出席".equals(attendance),
                        score,
                        notes
                    );
                    RecordDAO.addRecord(record);
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(dialog,
                        "学生 " + studentName + " 的得分必须是有效的数字！");
                    return;
                }
            }
            dialog.dispose();
        });

        panel.add(new JScrollPane(table), BorderLayout.CENTER);
        panel.add(saveBtn, BorderLayout.SOUTH);

        dialog.add(panel);
        dialog.setVisible(true);
    }
//记录考勤得分
    private static void exportScores(JDialog parent) {
        // 创建导出文件选择器
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("选择导出位置");
        fileChooser.setFileFilter(new FileNameExtensionFilter("CSV文件", "csv"));

        if (fileChooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            if (!file.getName().toLowerCase().endsWith(".csv")) {
                file = new File(file.getAbsolutePath() + ".csv");
            }

            try (PrintWriter writer = new PrintWriter(new FileWriter(file))) {
                // 写入表头
                writer.println("学生姓名,学号,班级,小组,考勤次数,平均得分");

                // 写入学生数据
                for (Student student : StudentDAO.getAllStudents()) {
                    ClassInfo classInfo = ClassDAO.getClassById(student.getClassId());
                    Group group = GroupDAO.getGroupById(student.getGroupId());
                    List<Record> records = RecordDAO.getRecordsByStudentId(student.getId());

                    int attendanceCount = 0;
                    int totalScore = 0;
                    for (Record record : records) {
                        if (record.isAttendance()) attendanceCount++;
                        totalScore += record.getScore();
                    }
                    double avgScore = records.isEmpty() ? 0 : (double) totalScore / records.size();

                    writer.printf("%s,%s,%s,%s,%d,%.2f\n",
                        student.getStudentName(),
                        student.getStudentId(),
                        classInfo != null ? classInfo.getClassName() : "",
                        group != null ? group.getGroupName() : "",
                        attendanceCount,
                        avgScore
                    );
                }

                JOptionPane.showMessageDialog(parent, "成绩导出成功！");
            } catch (IOException e) {
                JOptionPane.showMessageDialog(parent, "导出失败：" + e.getMessage());
            }
        }
    }
    //导出成绩
} 